﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using Baby.Framework.Comm;
using BabyShop.Site.Models;

namespace BabyShop.Site.Services
{
    public class UserService : BaseService<User>
    {
        public bool ValidateUser(string account,string passWord)
        {
            User user = DataServices.Users.Where(u => u.Account == account).FirstOrDefault();
            if(user != null) {
                string passKey = user.PassKey;
                string hashPass = EncryptionHelper.SymmetricDesEncode(passWord, passKey);
                return user.HashPass == hashPass;
            }
            return false;
        }

        public bool CreateUser(string email, string passWord,Guid modifyBy = default(Guid))
        {
            if(modifyBy == Guid.Empty)
                modifyBy = Guid.NewGuid();

            User user = new User
                                  {
                                      Email = email,
                                      Account = email,
                                      PassKey = BabyRandom.CreateRandomString(8),
                                      UserGuid = modifyBy
                                  };
            user.HashPass = EncryptionHelper.SymmetricDesEncode(passWord, user.PassKey);
            user.CommonColumns = new CommonColumns {ModifiedBy = modifyBy};
            DataServices.Users.Add(user);
            return DataServices.SaveChanges() > 0;
        }

        public User GetUserByAccount(string account)
        {
            return DataServices.Users.Where(u => u.Account == account).FirstOrDefault();
        }

        public bool ChangeUserPassword(string oldPass,string newPass,ref User currUser)
        {
            if(EncryptionHelper.SymmetricDesEncode(oldPass,currUser.PassKey) == currUser.HashPass) {
                currUser.HashPass = EncryptionHelper.SymmetricDesEncode(newPass, currUser.PassKey);
                DataServices.Entry(currUser).State = EntityState.Modified;

                return DataServices.SaveChanges() > 0;
            }
            return false;
        }
    }
}